package com.i2works.smartluolong.web.utils;

import com.i2works.smartluolong.utils.base.GlobalConstant;
import com.i2works.smartluolong.web.entity.user.UserAccountDO;
import com.i2works.smartluolong.web.shiro.SmartWebRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

/**
 * 用户登陆信息存储
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2016/1/17 14:57
 */
@Component
public class BaseModule {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 获取登陆用户
     */
    protected UserAccountDO getLoginUser() {
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        if (null != principals) {
            return (UserAccountDO) principals.iterator().next();
        }
        return null;
    }

    /**
     * 获取登陆用户ID
     */
    protected Integer getUserId() {
        return getLoginUser().getId();
    }
    
    /**
     * 获取登陆用户OPENID
     */
    protected String getUserOpenId() {
        return getLoginUser().getOpenId();
    }



    /**
     * 获取登陆账号
     */
    protected String getUserName() {
        return getLoginUser().getUserName();
    }

    /**
     * 获取邮箱
     */
    protected String getEmail() {
        return getLoginUser().getEmail();
    }

    /**
     * 获取会话ID
     */
    protected String getSessionId() {
        Session session = SecurityUtils.getSubject().getSession();
        if (session != null && session.getId() != null) {
            return String.valueOf(session.getId());
        }
        return null;
    }

    /**
     * 获取验证码KEY
     */
    protected String getVerifyKey() {
        return String.format(GlobalConstant.VERIFY_KEY, getSessionId());
    }

    /**
     * 获取sms验证码KEY
     */
    protected String getSMSKey() {
        return String.format(GlobalConstant.SMS_CODE_KEY, getSessionId());
    }

    /**
     * 更新用户信息
     */
    protected void updateUser(UserAccountDO userAccountDO) {
        BeanUtils.copyProperties(userAccountDO, getLoginUser());
    }

    /**
     * 清理认证缓存（用户信息）
     */
    protected void clearUserCache() {
        //清理认证缓存（用户信息）
        reloadCache(getRealm(SmartWebRealm.class), getUserName(), 1);

    }

    /**
     * 清理授权缓存(权限)
     */
    protected void clearAuthorCache() {
        //清理授权缓存(权限)
        reloadCache(getRealm(SmartWebRealm.class), getUserName(), 2);
    }

    /**
     * 清理shiro全部缓存（用户信息+权限）
     */
    protected void clearAllCache() {
        //清理授权缓存(权限)
        reloadCache(getRealm(SmartWebRealm.class), getUserName(), 3);

    }


    private <T> T getRealm(Class<T> clazz) {
        RealmSecurityManager securityManager = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        Realm realm = securityManager.getRealms().iterator().next();
        return clazz.cast(realm);
    }


    /**
     * 刷新shiro权限
     *
     * @param realm    realm
     * @param username 用户名
     * @param type     类型（1用户，2权限，3全部）
     */
    private void reloadCache(SmartWebRealm realm, String username, Integer type) {
        switch (type) {
            case 1:
                //清理认证缓存(用户)
                realm.clearUserCache();
                logger.info("清理认证缓存(用户)完成！");
                break;
            case 2:
                logger.info("清理授权缓存(权限)完成！");
                break;
            case 3:
                logger.info("清理shiro全部缓存完成！");
                break;
            default:
                break;
        }

    }




}
